<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/1/3
 * Time: 上午10:32
 */

namespace app\user\service;

use think\Exception;
use think\facade\Config;
use think\Controller;
use app\user\model\UserModel;
use app\user\model\UserTokenModel;
use think\facade\Request;

class UserService extends Controller
{
    /**
     *
     * @method 进行登录
     * @version
     * @User: bevan
     * @param $data  登录的账号 明文密码
     * @return 登录结果
     */
    public function login($data, $redirect = '/')
    {
        //判断登录账号类型
        if (cmf_validate_mobile($data['user_login'])) {
            //手机验证通过
            $user = UserModel::where('mobile', $data['user_login']);

        } elseif (cmf_validate_email($data['user_login'])) {
            //邮箱匹配
            $user = UserModel::where('user_email', $data['user_login']);

        } else {
            $user = UserModel::where('user_login', $data['user_login']);
        }

        $user = $user->whereIn('user_type', $data['user_type'])->find();

        if (!$user) {
            return ['code' => 4001, 'msg' => '用户名或密码不正确', 'data' => []];
        }
        if ($user['status'] == 0) {
            return ['code' => 4003, 'msg' => '账户被禁用', 'data' => []];
        }
        //验证密码
        if (cmf_crypt_password($data['user_pass']) == $user->user_pass) {
            //通过 登录成功 生成token
            $token = cmf_create_token();
            //token 入库
            $this->saveToken($user, $token);
            //更新最后登录ID\时间
            $user->last_login_time = time();
            (isset($data['login_ip']) && $data['login_ip']) ? $user->last_login_ip = $data['login_ip'] : '';
            $user->save();
            cookie('IG-Device-Type', null);
            cookie('IG-Token', null);
            cookie('IG-Token', $token);
            cookie('IG-Device-Type', 'web');
            $url = Request::param('redirect') ?: $redirect;
            return ['code' => 1001, 'msg' => '登录成功', 'data' => ['token' => $token], 'redirect' => $url];

        } else {
            return ['code' => 4002, 'msg' => '用户名或密码不正确', 'data' => []];
        }
    }

    /**
     *
     * @method 增加或新增user_token
     * @version
     * @User: bevan
     * @param $user
     * @param $token 最新的token
     * @return
     */
    public function saveToken($user, $token, $type = '')
    {
        $type = $type ?: cmf_get_user_device();

        $token_record = UserTokenModel::where([['uid', '=', $user->id], ['device_type', '=', $type]])->find();
        $expire_time = time() + Config::get('inge.token_expire_time') * 24 * 3600;

        if ($token_record) {
            //更新
            $token_record->expire_time = $expire_time;
            $token_record->token = $token;
            $token_record->device_type = $type;
            $token_record->save();
        } else {
            //插入
            UserTokenModel::create([
                'uid' => $user->id,
                'expire_time' => $expire_time,
                'token' => $token,
                'device_type' => $type,
            ]);
        }
    }

    /**
     *  更新token的有效期
     * @method
     * @version
     * @User:Thans
     * @return
     */
    public function updateTokenExpire($token)
    {
        return UserTokenModel::where('token', $token)
            ->setField('expire_time', time() + Config::get('inge.token_expire_time') * 24 * 3600);
    }

    /**
     *
     * @method
     * @version
     * @User:Thans
     * @return
     */
    public function logout()
    {

        $token = cmf_get_token();
        if ($token) {
            UserTokenModel::where('token', $token)->delete();
        }
        return true;
    }

    /**
     *
     * @method 更新用户自己的密码
     * @version
     * @User: bevan
     * @param $data
     * @return
     */
    public function updateSelfPass($data)
    {
        //先找到该人
        $login_msg = cmf_is_login();

        if ($login_msg['code'] != 1001) {
            return $login_msg;
        }
        $login_msg = $login_msg['data'];
        //验证新旧密码是否一致
        $user = UserModel::get($login_msg['uid']);

        if (cmf_crypt_password($data['old_pass']) != $user->user_pass) {
            return ['code' => 4001, 'msg' => '更新失败,原密码不匹配', 'data' => []];
        }

        //更新密码
        $user->user_pass = cmf_crypt_password($data['user_pass']);

        $user->save();

        return ['code' => 1001, 'msg' => '密码更新成功', 'data' => []];

    }

    /**
     *
     * @method 用户更新自己的信息
     * @version
     * @User: bevan
     * @param $data
     * @return
     */
    public function updateSelfInfo($data)
    {

        //验证登录
        $login_msg = cmf_is_login();

        if ($login_msg['code'] != 1001) {
            return $login_msg;
        }

        // 验证生日不能超过现在的时间
        $data['birthday'] = strtotime($data['birthday']);
        if ($data['birthday'] > time()) {
            return ['code' => 4001, 'msg' => '出生日期不能超过现在', 'data' => []];
        }

        $login_msg = $login_msg['data'];
        $uid = $login_msg['uid'];

        //验证唯一性 排除自身
        $result = UserModel::checkUnique($data, $uid);

        if (true !== $result) {
            return ['code' => 4001, 'msg' => $result, 'data' => []];
        }

        //更新
        try {
            $user = new UserModel;
            $user = $user->get($uid);
            $user->allowField(['sex', 'birthday', 'user_nickname', 'user_url', 'avatar', 'signature'])
                ->save($data);
        } catch (Exception $e) {
            return ['code' => 4001, 'msg' => $e->getMessage(), 'data' => []];
        }
        return ['code' => 1001, 'msg' => '更新成功', 'data' => []];
    }

}
